package cn.lingyangwl.agile.system.handler.config;

import cn.lingyangwl.agile.model.enums.ConfigKeyEnum;
import cn.lingyangwl.agile.model.module.config.param.BaseConfigParam;
import cn.lingyangwl.agile.model.module.config.param.WebSiteParam;
import cn.lingyangwl.agile.model.module.tenant.TenantContext;
import cn.lingyangwl.agile.system.model.entity.SysConfig;
import cn.lingyangwl.agile.system.model.rqrs.tenant.TenantOwnerUpdateReq;
import cn.lingyangwl.agile.system.model.rqrs.tenant.TenantResp;
import cn.lingyangwl.agile.system.service.SysTenantService;
import cn.lingyangwl.framework.tool.core.StringUtils;
import cn.lingyangwl.framework.tool.core.exception.BizException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Optional;

/**
 * @author shenguangyang
 */
@Component
public class WebSiteConfigHandler extends ConfigHandler {
    @Resource
    private SysTenantService tenantService;

    @Override
    public void doneWriteOps(SysConfig newConfig, BaseConfigParam<?> param) {
        WebSiteParam newParam = (WebSiteParam) param;
        TenantOwnerUpdateReq updateReq = new TenantOwnerUpdateReq();
        updateReq.setLogo(newParam.getLogo());
        updateReq.setName(newParam.getName());
        tenantService.updateOwnerTenant(updateReq);

        // 判断是否为使能存储/短信/邮箱, 如果使能某个渠道且使能的厂商发生变更, 就初始化
        if (StringUtils.isNotEmpty(newParam.getEnabledEmailConfigKey())) {
            handlerWriteOps(configManager.getByConfigKey(newParam.getEnabledEmailConfigKey()));
        }
        if (StringUtils.isNotEmpty(newParam.getEnabledStorageConfigKey())) {
            handlerWriteOps(configManager.getByConfigKey(newParam.getEnabledStorageConfigKey()));
        }
        if (StringUtils.isNotEmpty(newParam.getEnabledSmsConfigKey())) {
            handlerWriteOps( configManager.getByConfigKey(newParam.getEnabledSmsConfigKey()));
        }
    }

    @Override
    protected BaseConfigParam<?> doneReadOps(BaseConfigParam<?> param) {

        WebSiteParam newParam = (WebSiteParam) param;
        newParam = Optional.ofNullable(newParam).orElse(new WebSiteParam());
        String tenantId = TenantContext.get().getTenantId();

        TenantResp tenant = tenantService.getTenantById(tenantId);
        if (Objects.isNull(tenant)) {
            throw new BizException("租户不存在");
        }
        newParam.setTenantId(tenantId);
        newParam.setName(StringUtils.firstNonEmpty(newParam.getName(), tenant.getName()));
        newParam.setLogo(StringUtils.firstNonEmpty(newParam.getLogo(), tenant.getLogo()));

        return newParam;
    }

    @Override
    public ConfigKeyEnum configKey() {
        return ConfigKeyEnum.WEB_SITE;
    }
}
